package com.service.impl;

import com.dao.UserAccessDAO;
import com.model._do.login_do.LoginStatusDO;
import com.service.UserAccessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

@Service("userAccessService")
public class UserAccessServiceImpl implements UserAccessService {

    @Autowired
    private UserAccessDAO userAccessDAO;

    public String flushByCustomCode(LoginStatusDO status) {
        //create 10-minute-after time
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, +10);

        LoginStatusDO oldStatus = userAccessDAO.getByOpenId(status);
        if(oldStatus != null){
            Date now = new Date();

            //token not over time
            if(now.compareTo(oldStatus.getGmtLimit()) <= 0){
                status.setGmtLimit(calendar.getTime());
                userAccessDAO.flushStatus(status);
                return oldStatus.getCustomCode();
            }
            //token over time
            else {
                status.setGmtLimit(calendar.getTime());
                String newCustomCode = UUID.randomUUID().toString().replace("-","");
                status.setCustomCode(newCustomCode);
                userAccessDAO.addNewStatus(status);
                return newCustomCode;
            }
        } else {
            status.setGmtLimit(calendar.getTime());
            String newCustomCode = UUID.randomUUID().toString().replace("-","");
            status.setCustomCode(newCustomCode);
            userAccessDAO.addNewStatus(status);
            return newCustomCode;
        }
    }

    @Override
    public LoginStatusDO getByCustomCode(String customCode) {
        return userAccessDAO.getByCustomCode(customCode);
    }
}
